package com.dove.tcpclient;

import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {
    private Button bt_sendData;
    private LinearLayout ll_content;
    private BufferedOutputStream bos;
    private BufferedInputStream bis;
    private ReadThread readThread;
    private WriteRead writeRead;
    private int FROM_CLIENT = 0;
    private int FROM_SERVER = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        doConnect();
    }
    private void initView() {
        bt_sendData = findViewById(R.id.bt_sendData);
        ll_content = findViewById(R.id.ll_content);

        bt_sendData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                writeRead = new WriteRead();
                writeRead.start();
            }
        });
    }

    private void doConnect() {
        //子线程请求网络
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Socket socket = new Socket();
                    //建立Socket连接，需要服务端IP地址和端口号
                    socket.connect(new InetSocketAddress("172.16.201.80", 6666), 5 * 1000);
                    //通过Socket实例获取输入输出流，作为和服务器交换数据的通道
                    bis = new BufferedInputStream(socket.getInputStream());
                    bos = new BufferedOutputStream(socket.getOutputStream());

                    readThread = new ReadThread();
                    readThread.start();

                    Log.i("Socket","socket连接成功");
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("Socket","socket连接失败");
                }
            }
        }).start();
    }

    //启动一个线程，一直读取从服务端发送过来的消息
    private class ReadThread extends Thread {
        @Override
        public void run() {
            while (true) {
                byte[] data = new byte[1024];
                int size = 0;
                try {
                    //收到客服端发送的消息后，返回一个消息给客户端
                    while((size = bis.read(data)) != -1) {
                        String str = new String(data, 0, size);
                        Message msg = new Message();
                        msg.obj = new String(str);
                        mHandler.sendMessage(msg);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //启动一个线程，在子线程中发送数据给服务端
    private class WriteRead extends Thread{
        @Override
        public void run() {
            try {
                String iSay = "我说：老公老公，你还行吗？";
                bos.write(iSay.getBytes());
                //记得一定要flush一下
                bos.flush();
                showText(FROM_CLIENT, iSay);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String xifuerSay = msg.obj.toString();
            showText(FROM_SERVER, xifuerSay);
        }
    };

    //显示客户端与服务端之间的对话
    private void showText(final int type,final  String text) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TextView tv = new TextView(MainActivity.this);
                tv.setText(text);
                tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
                tv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                if (type == FROM_CLIENT) {
                    tv.setTextColor(Color.parseColor("#000000"));
                } else if (type == FROM_SERVER) {
                    tv.setTextColor(Color.parseColor("#ff0000"));
                }
                ll_content.addView(tv);
            }
        });
    }
}
